from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.executors.pool import ProcessPoolExecutor
from Day10.d03_new_statistics_tool import app
from Day10.models import db, Article
from sqlalchemy import func

# 创建执行器
executors = {
    # 默认使用进程的方式执行定时任务
    # 3代表同一时刻,最多只有3个进程同时执行
    'default': ProcessPoolExecutor(3)
}
# 创建调度器对象
scheduler = BlockingScheduler(executors=executors)
# 定义修复统计数据的函数
def fix_statistics():
    # 创建应用上下文环境,执行命令
    with app.app_context():
        ret = db.session.query(Article.user_id, func.count(Article.id)).filter(Article.status == Article.STATUS.APPROVED). \
            group_by(Article.user_id).all()

        # 修改缓存中发布文章数量
        key = 'count:user:arts'
        pl = app.redis_master.pipeline()
        pl.delete(key)
        data = []
        # ret:[(user_id, count)]
        for user_id, count in ret:
            # data = [count1, user_id1, count2, user_id2]
            data.append(count)
            data.append(user_id)
        # zadd(key, score, member, score2, member2)
        pl.zadd(key, *data)
        pl.execute()
    print('更新完成')
# 添加执行任务 使用cron指定每天在2点执行
# scheduler.add_job(fix_statistics, 'cron', hour=2, minute=0)

scheduler.add_job(fix_statistics, 'date') # 立刻执行

# 添加执行任务 使用cron 指定每天在14:46
scheduler.add_job(fix_statistics, 'cron', hour=14, minute=46)

if __name__ == '__main__':
    # 启动调度器
    scheduler.start()
